package priv.xp.androidexample.adapter

import android.text.format.DateFormat
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.paging.PagedListAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import priv.xp.androidexample.databinding.CellImagesGirlBinding
import priv.xp.androidexample.model.Girl

class GirlAdapter : PagedListAdapter<Girl, GirlAdapter.ViewHolder>(diffCallback) {
    companion object {
        val diffCallback = object : DiffUtil.ItemCallback<Girl>() {
            override fun areItemsTheSame(oldItem: Girl, newItem: Girl): Boolean {
                return oldItem._id == newItem._id
            }

            override fun areContentsTheSame(oldItem: Girl, newItem: Girl): Boolean {
                return oldItem == newItem
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = CellImagesGirlBinding.inflate(LayoutInflater.from(parent.context), parent, false)

        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = getItem(position)
        holder.bind(item)
    }

    class ViewHolder(private val binding: CellImagesGirlBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(item: Girl?) {
            binding.txDate.text = DateFormat.format("yyyy年MM月dd", item?.publishedAt)
            Glide.with(binding.root).load(item?.url).into(binding.imgGirl)
        }
    }
}
